const xml2js = require('xml2js');

module.exports = options => {
    return async function xml(ctx, next) {
        const req = ctx.req;
        let buf = '';
        let result = null;
        //获取xml
        buf = await getXML(req, buf);
        //解析xml
        result = await parseXML(buf);
        //格式化解析后的xml
        result = await formatMessage(result.xml)
        //传递给控制器使用
        ctx.request.body = result;

        await next()
    }
    /**
     * 获取原始xml数据
     */
    function getXML(req, buf) {
        req.on('data', chunk => {
            buf += chunk
        })
        return new Promise((resolve, reject) => {
            req.on('end', () => {
                resolve(buf)
            })
        });
    }
    /**
     * 解析原始xml
     */
    function parseXML(xml) {
        return new Promise((resolve, reject) => {
            xml2js.parseString(xml, { trim: true }, function (err, obj) {
                if (err) {
                    return reject(err);
                }
                resolve(obj);
            });
        });
    }
    /**
     * 将xml2js解析出来的对象转换成直接可访问的对象
     */
    async function formatMessage(result) {
        var message = {};
        if (typeof result === 'object') {
            for (var key in result) {
                if (!(result[key] instanceof Array) || result[key].length === 0) {
                    continue;
                }
                if (result[key].length === 1) {
                    var val = result[key][0];
                    if (typeof val === 'object') {
                        message[key] = formatMessage(val);
                    } else {
                        message[key] = (val || '').trim();
                    }
                } else {
                    message[key] = result[key].map(function (item) {
                        return formatMessage(item);
                    });
                }
            }
        }
        return message;
    }

}